import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { Tabs, List, Row, Col, Input, Collapse } from 'antd';
// 引入日期组件
import Second from './Second'; //秒
import Minute from './Minute'; //分
import Hour from './Hour'; //时
import Day from './Day'; //日
import Week from './Week'; //周
import Month from './Month'; //月
import Year from './Year'; //年
import CronParser from 'cron-parser'; //npm包
import CronParse from '../common/parse-lib';
import '../common/index.less';
import moment from 'moment';
import { OneModal } from '@/components/one-ui';
const dateMinute = 'YYYY-MM-DD HH:mm';
export default function Cron(props: any) {
  const date = new Date(); //时间
  const { Panel } = Collapse;
  const { TabPane } = Tabs; //组件
  const [from, setFrom] = useState({
    //初始数据
    activeKey: 'second',
    year: {
      type: '',
      start: date.getFullYear(),
      end: date.getFullYear() + 1,
    },
    month: {
      start: 1,
      end: 2,
      begin: 1,
      beginEvery: 1,
      type: '*',
      some: ['1'],
    },
    week: {
      start: '1',
      end: '2',
      last: '1',
      begin: 1,
      beginEvery: '1',
      type: '?',
      some: ['1'],
    },
    day: {
      last: 1,
      closeWorkDay: 1,
      start: 1,
      end: 2,
      begin: 1,
      beginEvery: 1,
      type: '*',
      some: ['1'],
    },
    hour: {
      //小时
      start: 0,
      end: 1,
      begin: 0,
      beginEvery: 1,
      type: '*',
      some: ['0'],
    },
    minute: {
      //分钟
      start: 0,
      end: 1,
      begin: 0,
      beginEvery: 1,
      type: '*',
      some: ['0'],
    },
    second: {
      // 秒数
      start: 0, //开始
      end: 1, //结束
      begin: 0,
      beginEvery: 1,
      type: '*',
      some: ['0', '1'],
    },
    // runTime: [],
    cron: '0 0 0 * * ?',
  });
  const [runTime, setrunTime] = useState([]);
  const [initVal, setInit] = useState('0 0 0 * * ?'); // 表格的初始值
  function initValue() {
    let value = initVal;
    value = value.toUpperCase();
    const valuesArray = value.split(' ');
    let newState: any = { ...from };
    newState.second.value = valuesArray[0] || '';
    newState.minute.value = valuesArray[1] || '';
    newState.hour.value = valuesArray[2] || '';
    newState.day.value = valuesArray[3] || '';
    newState.month.value = valuesArray[4] || '';
    newState.week.value = valuesArray[5] || '';
    newState.year.value = valuesArray[6] || '';
    setFrom(newState);
    parse();
  }
  function parse() {
    let { year, month, week, day, hour, minute, second }: any = from;
    if (year.value.indexOf('-') > -1) {
      year.type = 'period';
      year.start = year.value.split('-')[0];
      year.end = year.value.split('-')[1];
    } else {
      year.type = year.value;
    }
    if (week.value.indexOf('-') > -1) {
      week.type = 'period';
      week.start = week.value.split('-')[0];
      week.end = week.value.split('-')[1];
    } else if (week.value.indexOf('L') > -1) {
      week.type = 'last';
      week.last = week.value.split('L')[0] || 1;
    } else if (week.value.indexOf('#') > -1) {
      week.type = 'beginInterval';
      week.begin = week.value.split('#')[1];
      week.beginEvery = week.value.split('#')[0];
    } else if (week.value.indexOf(',') > -1 || /^[0-9]+$/.test(week.value)) {
      week.type = 'some';
      week.some = week.value.split(',');
    } else {
      week.type = week.value || '?';
    }

    if (month.value.indexOf('-') > -1) {
      month.type = 'period';
      month.start = month.value.split('-')[0];
      month.end = month.value.split('-')[1];
    } else if (month.value.indexOf('/') > -1) {
      month.type = 'beginInterval';
      month.begin = month.value.split('/')[0];
      month.beginEvery = month.value.split('/')[1];
    } else if (month.value.indexOf(',') > -1 || /^[0-9]+$/.test(month.value)) {
      month.type = 'some';
      month.some = month.value.split(',');
    } else {
      month.type = month.value || '?';
    }

    if (day.value.indexOf('-') > -1) {
      day.type = 'period';
      day.start = day.value.split('-')[0];
      day.end = day.value.split('-')[1];
    } else if (day.value.indexOf('W') > -1) {
      day.type = 'closeWorkDay';
      day.closeWorkDay = day.value.split('W')[0] || 1;
    } else if (day.value.indexOf('L') > -1) {
      day.type = 'last';
      day.last = day.value.split('L')[0] || 1;
    } else if (day.value.indexOf('/') > -1) {
      day.type = 'beginInterval';
      day.begin = day.value.split('/')[0];
      day.beginEvery = day.value.split('/')[1];
    } else if (day.value.indexOf(',') > -1 || /^[0-9]+$/.test(day.value)) {
      day.type = 'some';
      day.some = day.value.split(',');
    } else {
      day.type = day.value || '?';
    }

    if (hour.value.indexOf('-') > -1) {
      hour.type = 'period';
      hour.start = hour.value.split('-')[0];
      hour.end = hour.value.split('-')[1];
    } else if (hour.value.indexOf('/') > -1) {
      hour.type = 'beginInterval';
      hour.begin = hour.value.split('/')[0];
      hour.beginEvery = hour.value.split('/')[1];
    } else if (hour.value.indexOf(',') > -1 || /^[0-9]+$/.test(hour.value)) {
      hour.type = 'some';
      hour.some = hour.value.split(',');
    } else {
      hour.type = hour.value || '?';
    }

    if (minute.value.indexOf('-') > -1) {
      minute.type = 'period';
      minute.start = minute.value.split('-')[0];
      minute.end = minute.value.split('-')[1];
    } else if (minute.value.indexOf('/') > -1) {
      minute.type = 'beginInterval';
      minute.begin = minute.value.split('/')[0];
      minute.beginEvery = minute.value.split('/')[1];
    } else if (
      minute.value.indexOf(',') > -1 ||
      /^[0-9]+$/.test(minute.value)
    ) {
      minute.type = 'some';
      minute.some = minute.value.split(',');
    } else {
      minute.type = minute.value || '?';
    }

    if (second.value.indexOf('-') > -1) {
      second.type = 'period';
      second.start = second.value.split('-')[0];
      second.end = second.value.split('-')[1];
    } else if (second.value.indexOf('/') > -1) {
      second.type = 'beginInterval';
      second.begin = second.value.split('/')[0];
      second.beginEvery = second.value.split('/')[1];
    } else if (
      second.value.indexOf(',') > -1 ||
      /^[0-9]+$/.test(second.value)
    ) {
      second.type = 'some';
      second.some = second.value.split(',');
    } else {
      second.type = second.value || '?';
    }
    setFrom({
      ...from,
      year: { ...year },
      month: { ...month },
      week: { ...week },
      day: { ...day },
      hour: { ...hour },
      minute: { ...minute },
      second: { ...second },
    });
  }
  // 初始化
  useEffect(() => {
    initValue();
  }, []);
  //
  useEffect(() => {
    updataInit(from.cron);
  }, []);
  const updataInit = (str: string) => {
    let tempArr: any = [];
    const weekCron = str.split(' ')[5];
    // try {
    if (weekCron !== '?') {
      const interval = CronParser.parseExpression(String(str).trim());
      for (let i = 0; i < 5; i++) {
        const temp = moment(interval.next().toString()).format(dateMinute);
        tempArr.push(temp);
      }
    } else {
      const core = new CronParse();
      tempArr = core.expressionChange(String(str).trim());
    }
    // } catch (error) {
    //     setrunTime(['无执行任务'])
    // }

    props.cronState(str);
    setrunTime(tempArr);
  };
  // tab事件
  const onChange = (key: string) => {};
  const onChanges = (state: any) => {
    setFrom({ ...from, ...state });
    culcCron({ ...from, ...state });
  };
  function n2s(number: any) {
    if (typeof number === 'number' && number !== NaN) {
      return `${number}`;
    }
    return number;
  }
  function culcCron({ year, month, week, day, hour, minute, second }: any) {
    if (year.type === 'period') {
      year.value = `${n2s(year.start)}-${n2s(year.end)}`;
    } else {
      year.value = year.type;
    }
    if (month.type === 'period') {
      month.value = `${n2s(month.start)}-${n2s(month.end)}`;
    } else if (month.type === 'beginInterval') {
      month.value = `${n2s(month.begin)}/${n2s(month.beginEvery)}`;
    } else if (month.type === 'some') {
      month.value = month.some.join(',');
    } else {
      month.value = month.type;
    }
    if (week.type === 'period') {
      week.value = `${n2s(week.start)}-${n2s(week.end)}`;
    } else if (week.type === 'beginInterval') {
      week.value = `${n2s(week.beginEvery)}#${n2s(week.begin)}`;
    } else if (week.type === 'last') {
      week.value = n2s(week.last) + 'L';
    } else if (week.type === 'some') {
      week.value = week.some.join(',');
    } else {
      week.value = week.type;
    }
    if (day.type === 'period') {
      day.value = `${n2s(day.start)}-${n2s(day.end)}`;
    } else if (day.type === 'beginInterval') {
      day.value = `${n2s(day.begin)}/${n2s(day.beginEvery)}`;
    } else if (day.type === 'closeWorkDay') {
      day.value = n2s(day.closeWorkDay || 1) + 'W';
    } else if (day.type === 'last') {
      // day.value = n2s(day.last || 1) + "L";
      day.value = 'L';
    } else if (day.type === 'some') {
      day.value = day.some.join(',');
    } else {
      day.value = day.type;
    }
    if (hour.type === 'period') {
      hour.value = `${n2s(hour.start)}-${n2s(hour.end)}`;
    } else if (hour.type === 'beginInterval') {
      hour.value = `${n2s(hour.begin)}/${n2s(hour.beginEvery)}`;
    } else if (hour.type === 'some') {
      hour.value = hour.some.join(',');
    } else {
      hour.value = hour.type;
    }
    if (minute.type === 'period') {
      minute.value = `${n2s(minute.start)}-${n2s(minute.end)}`;
    } else if (minute.type === 'beginInterval') {
      minute.value = `${n2s(minute.begin)}/${n2s(minute.beginEvery)}`;
    } else if (minute.type === 'some') {
      minute.value = minute.some.join(',');
    } else {
      minute.value = minute.type;
    }
    if (second.type === 'period') {
      second.value = `${n2s(second.start)}-${n2s(second.end)}`;
    } else if (second.type === 'beginInterval') {
      second.value = `${n2s(second.begin)}/${n2s(second.beginEvery)}`;
    } else if (second.type === 'some') {
      second.value = second.some.join(',');
    } else {
      second.value = second.type;
    }
    // 修改计算时间
    updataInit(
      `${second.value} ${minute.value} ${hour.value} ${day.value} ${month.value} ${week.value} ${year.value}`,
    );
  }
  // 结构
  const { year, month, week, day, hour, minute, second, activeKey }: any = from;
  return (
    <OneModal
      title="复杂提醒"
      centered
      width="900px"
      open={true}
      onCancel={() => {
        props?.handleCancel();
      }}
      onOk={() => {
        props?.handleClick();
      }}
    >
      <div className="cron_boxsis">
        {/* ---------------------------------------------------------------------------------tab切换 */}
        <Tabs onChange={onChange} type="card" className="">
          <TabPane tab="秒钟" key="1">
            <Second
              width="900px"
              {...from}
              onchange={(val: any) => {
                onChanges({ second: val });
              }}
            />
          </TabPane>
          <TabPane tab="分钟" key="2">
            <Minute
              width="900px"
              {...from}
              onchange={(val: any) => {
                onChanges({ minute: val });
              }}
            />
          </TabPane>
          <TabPane tab="小时" key="3">
            <Hour
              width="900px"
              {...from}
              onchange={(val: any) => {
                onChanges({ hour: val });
              }}
            />
          </TabPane>
          <TabPane tab="日" key="4">
            <Day
              {...from}
              onchange={(val: any) => {
                onChanges({ day: val });
              }}
            />
          </TabPane>
          <TabPane tab="周" key="5">
            <Week
              {...from}
              onchange={(val: any) => {
                onChanges({ week: val });
              }}
            />
          </TabPane>
          <TabPane tab="月" key="6">
            <Month
              {...from}
              onchange={(val: any) => {
                onChanges({ month: val });
              }}
            />
          </TabPane>

          <TabPane tab="年" key="7">
            <Year
              {...from}
              onchange={(val: any) => {
                onChanges({ year: val });
              }}
            />
          </TabPane>
        </Tabs>
        {/* ----------------展示数据  从父级传递子级的数据  在子级修改后返回  父级在传递给这里 修改input */}
        <List bordered style={{ marginTop: 10 }}>
          <List.Item>
            <Row gutter={5} style={{ width: '100%', textAlign: 'center' }}>
              <Col span={3}>秒</Col>
              <Col span={3}>分</Col>
              <Col span={3}>时</Col>
              <Col span={3}>日</Col>
              <Col span={3}>月</Col>
              <Col span={3}>周</Col>
              <Col span={3}>年</Col>
            </Row>
          </List.Item>
          <List.Item>
            <Row gutter={5} style={{ width: '100%', textAlign: 'center' }}>
              <Col span={3}>
                <Input disabled value={second.value}></Input>
              </Col>
              <Col span={3}>
                <Input disabled value={minute.value}></Input>
              </Col>
              <Col span={3}>
                <Input disabled value={hour.value}></Input>
              </Col>
              <Col span={3}>
                <Input disabled value={day.value}></Input>
              </Col>
              <Col span={3}>
                <Input disabled value={month.value}></Input>
              </Col>
              <Col span={3}>
                <Input disabled value={week.value}></Input>
              </Col>
              <Col span={3}>
                <Input disabled value={year.value}></Input>
              </Col>
            </Row>
          </List.Item>
        </List>
        <div>
          <Collapse accordion>
            <Panel header="最近执行的5次" key="1">
              <List
                bordered
                dataSource={runTime}
                renderItem={(item, index) => (
                  <List.Item>
                    第{index + 1}执行时间： {item}
                  </List.Item>
                )}
              />
            </Panel>
          </Collapse>
        </div>
      </div>
    </OneModal>
  );
}
